﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.SaleOrders;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.SaleOrders;

namespace Reporting.API.Application.CommandHandler.SaleOrders
{
    /// <summary>
    /// 添加 销售订单
    /// </summary>
    public class AddSaleOrderCommandHandler : IRequestHandler<AddSaleOrderCommand, ApiResult>
    {
        private readonly ISaleOrderRepository _saleOrderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddSaleOrderCommandHandler> _logger;

        public AddSaleOrderCommandHandler(ILogger<AddSaleOrderCommandHandler> logger, IMapper mapper, ISaleOrderRepository saleOrderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _saleOrderRepository = saleOrderRepository;
        }

        public async Task<ApiResult> Handle(AddSaleOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 将 DTO 映射为实体类
                var SaleOrders = _mapper.Map<SaleOrder>(request);

                // 调用仓储层添加用户
                var addedUser = await _saleOrderRepository.InsertAsync(SaleOrders);

                // 返回成功结果  StatusCodeEnum
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "销售订单添加失败");
                throw;
            }
        }







    }
}
